#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="qrcode-system"

# 从 config.js 读取 productionDomain 字段（优先），否则 fallback 到 system-config.json 的 baseUrl
CONFIG_JS="config.js"
if [ -f "$CONFIG_JS" ]; then
    PROD_DOMAIN=$(grep 'productionDomain:' "$CONFIG_JS" | head -n1 | awk -F "'" '{print $2}')
fi
if [ -z "$PROD_DOMAIN" ]; then
    # fallback 到 system-config.json 的 baseUrl
    CONFIG_FILE="system-config.json"
    if [ -f "$CONFIG_FILE" ]; then
        BASE_URL=$(grep '"baseUrl"' "$CONFIG_FILE" | head -n1 | awk -F '"' '{print $4}')
        PROD_DOMAIN=$(echo "$BASE_URL" | sed -E 's#^https?://([^/:]+).*#\1#')
    fi
fi
if [ -z "$PROD_DOMAIN" ]; then
    echo "❌ 未检测到域名配置，请在 config.js 的 productionDomain 字段或 system-config.json 的 baseUrl 字段中配置域名！"
    exit 1
fi

# 替换 nginx.conf 中的 {{DOMAIN}} 占位符
cp nginx.conf nginx.conf.tmp
sed "s/{{DOMAIN}}/$PROD_DOMAIN/g" nginx.conf.tmp > nginx.conf.final
mv nginx.conf.final nginx.conf
rm -f nginx.conf.tmp

# 替换 docker-compose.yml 中的 {{DOMAIN}} 占位符
cp docker-compose.yml docker-compose.yml.tmp
sed "s/{{DOMAIN}}/$PROD_DOMAIN/g" docker-compose.yml.tmp > docker-compose.yml.final
mv docker-compose.yml.final docker-compose.yml
rm -f docker-compose.yml.tmp

DOMAIN="$PROD_DOMAIN"
SSL_KEY="ssl/${DOMAIN}.key"
SSL_CRT="ssl/${DOMAIN}.crt"

echo -e "${BLUE}🚀 HTTPS扫码管理系统启动脚本${NC}"
echo "=================================="

# 检查Docker是否安装
check_docker() {
    echo -e "${YELLOW}🔍 检查Docker环境...${NC}"
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}❌ Docker未安装，请先安装Docker${NC}"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        echo -e "${RED}❌ Docker Compose未安装，请先安装Docker Compose${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ Docker环境检查通过${NC}"
}

# 检查SSL证书
check_ssl() {
    echo -e "${YELLOW}🔍 检查SSL证书...${NC}"
    
    if [ ! -f "$SSL_KEY" ]; then
        echo -e "${RED}❌ SSL私钥文件不存在: $SSL_KEY${NC}"
        echo "请将您的SSL私钥文件放置到: $SSL_KEY"
        exit 1
    fi
    
    if [ ! -f "$SSL_CRT" ]; then
        echo -e "${RED}❌ SSL证书文件不存在: $SSL_CRT${NC}"
        echo "请将您的SSL证书文件放置到: $SSL_CRT"
        exit 1
    fi
    
    # 验证证书格式
    if ! openssl rsa -in "$SSL_KEY" -check -noout >/dev/null 2>&1; then
        echo -e "${RED}❌ SSL私钥格式错误${NC}"
        exit 1
    fi
    
    if ! openssl x509 -in "$SSL_CRT" -text -noout >/dev/null 2>&1; then
        echo -e "${RED}❌ SSL证书格式错误${NC}"
        exit 1
    fi
    
    # 检查证书和私钥是否匹配
    CERT_MODULUS=$(openssl x509 -in "$SSL_CRT" -modulus -noout | openssl md5)
    KEY_MODULUS=$(openssl rsa -in "$SSL_KEY" -modulus -noout | openssl md5)
    
    if [ "$CERT_MODULUS" != "$KEY_MODULUS" ]; then
        echo -e "${RED}❌ SSL证书和私钥不匹配${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ SSL证书检查通过${NC}"
}

# 停止现有服务
stop_services() {
    echo -e "${YELLOW}🛑 停止现有服务...${NC}"
    docker-compose down 2>/dev/null || true
    echo -e "${GREEN}✅ 服务已停止${NC}"
}

# 清理资源
clean_resources() {
    echo -e "${YELLOW}🧹 清理Docker资源...${NC}"
    docker system prune -f >/dev/null 2>&1
    echo -e "${GREEN}✅ 资源清理完成${NC}"
}

# 构建镜像
build_image() {
    echo -e "${YELLOW}🔨 构建Docker镜像...${NC}"
    if docker-compose build --no-cache; then
        echo -e "${GREEN}✅ 镜像构建成功${NC}"
    else
        echo -e "${RED}❌ 镜像构建失败${NC}"
        exit 1
    fi
}

# 启动服务
start_services() {
    echo -e "${YELLOW}🚀 启动服务...${NC}"
    if docker-compose up -d; then
        echo -e "${GREEN}✅ 服务启动成功${NC}"
    else
        echo -e "${RED}❌ 服务启动失败${NC}"
        exit 1
    fi
}

# 等待服务启动
wait_services() {
    echo -e "${YELLOW}⏳ 等待服务启动...${NC}"
    local max_attempts=15
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if docker-compose ps | grep -q "Up"; then
            echo -e "${GREEN}✅ 服务启动完成${NC}"
            break
        fi
        
        echo -e "${YELLOW}⏳ 等待服务启动... (尝试 $attempt/$max_attempts)${NC}"
        sleep 3
        attempt=$((attempt + 1))
    done
    
    if [ $attempt -gt $max_attempts ]; then
        echo -e "${RED}❌ 服务启动超时${NC}"
        show_logs
        exit 1
    fi
}

# 检查服务状态
check_status() {
    echo -e "${YELLOW}📊 检查服务状态...${NC}"
    echo ""
    echo "📋 容器状态:"
    docker-compose ps
    echo ""
    
    echo "🔍 详细状态:"
    docker-compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"
    echo ""
    
    echo "💾 资源使用:"
    docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"
}

# 测试连接
test_connections() {
    echo -e "${YELLOW}🔍 测试连接...${NC}"
    
    # 测试HTTP重定向
    echo "测试HTTP重定向..."
    if curl -I http://localhost 2>/dev/null | grep -q "301\|302"; then
        echo -e "${GREEN}✅ HTTP重定向正常${NC}"
    else
        echo -e "${RED}⚠️  HTTP重定向失败${NC}"
    fi
    
    # 测试HTTPS连接
    echo "测试HTTPS连接..."
    if curl -k -I https://localhost 2>/dev/null | grep -q "200\|301\|302"; then
        echo -e "${GREEN}✅ HTTPS连接正常${NC}"
    else
        echo -e "${RED}⚠️  HTTPS连接失败${NC}"
    fi
    
    # 测试直接访问Node.js HTTPS
    echo "测试Node.js HTTPS..."
    if curl -k -I https://localhost:10443 2>/dev/null | grep -q "200\|301\|302"; then
        echo -e "${GREEN}✅ Node.js HTTPS正常${NC}"
    else
        echo -e "${RED}⚠️  Node.js HTTPS失败${NC}"
    fi
}

# 显示日志
show_logs() {
    echo -e "${YELLOW}📋 显示服务日志...${NC}"
    echo ""
    echo "=== Node.js 应用日志 ==="
    docker-compose logs qrcode-system --tail=10
    echo ""
    echo "=== Nginx 日志 ==="
    docker-compose logs nginx --tail=10
}

# 显示访问信息
show_access_info() {
    echo ""
    echo "=================================="
    echo -e "${GREEN}🎉 部署完成${NC}"
    echo "=================================="
    echo -e "${BLUE}📋 服务信息：${NC}"
    echo "   - 项目名称: $PROJECT_NAME"
    echo "   - 域名: $DOMAIN"
    echo "   - HTTP端口: 48888"
    echo "   - HTTPS端口: 10443"
    echo "   - Nginx端口: 80/443"
    echo ""
    echo -e "${BLUE}🌐 访问地址：${NC}"
    echo "   - 主访问: https://$DOMAIN"
    echo "   - 直接访问: https://$DOMAIN:10443"
    echo "   - HTTP访问: http://$DOMAIN:48888"
    echo ""
    echo -e "${BLUE}🔧 管理命令：${NC}"
    echo "   - 查看状态: docker-compose ps"
    echo "   - 查看日志: docker-compose logs"
    echo "   - 重启服务: docker-compose restart"
    echo "   - 停止服务: docker-compose down"
    echo ""
    echo -e "${GREEN}🌐 推荐访问: https://$DOMAIN${NC}"
}

# 主函数
main() {
    check_docker
    check_ssl
    stop_services
    clean_resources
    build_image
    start_services
    wait_services
    check_status
    test_connections
    show_access_info
}

# 处理命令行参数
case "${1:-}" in
    "status")
        check_status
        ;;
    "logs")
        show_logs
        ;;
    "restart")
        stop_services
        start_services
        wait_services
        check_status
        ;;
    "stop")
        stop_services
        ;;
    "clean")
        stop_services
        clean_resources
        ;;
    "help"|"-h"|"--help")
        echo "使用方法: $0 [命令]"
        echo ""
        echo "命令:"
        echo "  (无参数)  启动完整部署流程"
        echo "  status    查看服务状态"
        echo "  logs      查看服务日志"
        echo "  restart   重启服务"
        echo "  stop      停止服务"
        echo "  clean     清理资源"
        echo "  help      显示帮助"
        ;;
    *)
        main
        ;;
esac 